package com.edu.dao;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.InputStream;
import java.io.InputStreamReader;

public class MyBatisUtil {
    private static SqlSessionFactory factory;
    /*
     * 在静态代码块下，factory只会被创建一次
     */
    static{
        try {
            String resource= "mybatis/mybatis-config.xml";
            InputStream is= Resources.getResourceAsStream(resource);
            factory=new SqlSessionFactoryBuilder().build(new InputStreamReader(is));
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public static SqlSession createSession(){
        return factory.openSession(false);//true为自动提交事务，true为默认值
    }

    /**
     * 关闭SqlSession对象
     * @param session
     */
    public static void closeSession(SqlSession session){
        if (session!=null) {
            session.close();
        }
    }
}
